package com.zhaopin.controller;

import com.zhaopin.entity.Result;
import com.zhaopin.entity.User;
import com.zhaopin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yin.peide
 * @date 2021-11-03 15:31
 */
@RestController
@RequestMapping("/user")
public class UserController {

    //增删改查增加 post:增 delete:删 put:改 get:查
    @Autowired
    private UserService userService;

    @Autowired
    MessageSource messageSource;

    /**
     * 查询用户
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getUser(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        //LocaleContextHolder 就是一个Locale持有器  springmvc底层会自动将LocalResovler中语言设置进去
        String messge = messageSource.getMessage("user.query.success", null, LocaleContextHolder.getLocale());
        return new Result<User>(200, messge, user);
    }

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    @PostMapping("/add")
    public Result putUser(@RequestBody User user) {
        userService.add(user);
        return new Result<User>(200, "新增用户成功", user);
    }

    /**
     * 更新用户
     *
     * @param user
     * @return
     */
    @PutMapping("/{id}")
    public Result updateUser(@RequestBody User user) {
        userService.update(user);
        return new Result<User>(200, "更新成功", user);
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        userService.delete(id);
        return new Result<User>(200, "删除用户成功");
    }

    /**
     * 查询所有的用户
     *
     * @return
     */
    @GetMapping("/getalluser")
    public Result getAllUser() {
        List<User> allUser = userService.getAllUser();
        return new Result<List<User>>(200, "所有用户", allUser);
    }


}
